package com.common.www.controller.project;

import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.TabulationExtracting;
import com.common.www.bean.entity.project.BiddingCompany;
import com.common.www.bean.entity.project.Project;
import com.common.www.bean.entity.project.SupplyCompany;
import com.common.www.bean.entity.tabulation.*;
import com.common.www.bean.vo.*;
import com.common.www.service.programme.PrecipitateDbService;
import com.common.www.service.programme.PrecipitateSsdbService;
import com.common.www.service.programme.TabulationExtractingService;
import com.common.www.service.project.BiddingCompanyService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.StatisticalAnalysisService;
import com.common.www.service.project.SupplyCompanyService;
import com.common.www.service.tabulation.*;
import com.common.www.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/statistical"})
@Api(tags = "MGT 统计分析管理接口")
public class MGTStatisticalAnalysisController {
    @Autowired
    private BiddingCompanyService biddingCompanyService;
    @Autowired
    private InnerBidBaseTabulationService innerBidBaseTabulationService;
    @Autowired
    private OuterBidBaseTabulationService outerBidBaseTabulationService;
    @Autowired
    private InnerTabulationService innerTabulationService;
    @Autowired
    private OuterTabulationService outerTabulationService;
    @Autowired
    private StatisticalAnalysisService analysisService;
    @Autowired
    private TabulationExtractingService extractingService;
    @Autowired
    private SupplyCompanyService supplyCompanyService;
    @Autowired
    private PrecipitateSsdbService precipitateSsdbService;
    @Autowired
    private PrecipitateDbService precipitateDbService;
    @Autowired
    private ProjectService projectService;


    @ApiOperation(value = "供应商等组合信息-排名", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getRankingProcess", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getRankingProcess(Long projectId, Integer innerOuterType) throws InvocationTargetException, IllegalAccessException {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        //查询在回标1到回标4的内外线数据
        hashMap.put("jieDuan_ge", 2);
        hashMap.put("jieDuan_le", 5);
        if (innerOuterType != null && innerOuterType != 0) {
            hashMap.put("innerOuterType", innerOuterType);
        }
        hashMap.put("flag", 1);
        List<TabulationExtracting> extractingList = extractingService.getListLogic(hashMap, null);
        //查询内线和外线标底
        HashMap hashMap1 = new HashMap();
        hashMap1.put("project.id", projectId);
        hashMap1.put("jieDuan", 1);
        hashMap1.put("flag", 1);
        List<TabulationExtracting> extractingBdList = extractingService.getListLogic(hashMap1, null);
        List<Map<String, Object>> paiMingList = analysisService.getPaiMingList(extractingList, extractingBdList);
        return R.ok(paiMingList);
    }


    @ApiOperation(value = "导出供应商等组合信息-排名", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/exportRankingProcess", method = RequestMethod.GET)
    public Result exportRankingProcess(Long projectId, Integer innerOuterType) throws InvocationTargetException, IllegalAccessException {
        Project project = projectService.findOne(projectId);
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        //查询在回标1到回标4的内外线数据
        hashMap.put("jieDuan_ge", 2);
        hashMap.put("jieDuan_le", 5);
        if (innerOuterType != null && innerOuterType != 0) {
            hashMap.put("innerOuterType", innerOuterType);
        }
        hashMap.put("flag", 1);
        List<TabulationExtracting> extractingList = extractingService.getListLogic(hashMap, null);
        //查询内线和外线标底
        HashMap hashMap1 = new HashMap();
        hashMap1.put("project.id", projectId);
        hashMap1.put("jieDuan", 1);
        hashMap1.put("flag", 1);
        List<TabulationExtracting> extractingBdList = extractingService.getListLogic(hashMap1, null);
        List<Map<String, Object>> pmList = analysisService.getPaiMingList(extractingList, extractingBdList);
        //准备导出
        String fileName = extractingBdList.get(0).getProject().getName();
        XSSFWorkbook workbook = analysisService.exportPaiMing(pmList, project);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "高低压商务排名-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation(value = "投标报价纵向对比", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getVerticalStatis", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getVerticalStatis(Long projectId, Integer innerOuterType, Integer jieDuan) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);

        if (innerOuterType == 1) {
            //投标报价纵向对比-内线
            List<VerticalStatisCollectVo> sortedList = analysisService.getVerticalStatis(companyList, projectId, jieDuan);
            return R.ok(sortedList);
        } else {
            //投标报价纵向对比-内线(暂无)
            List<OuterTabulation> outerTabulationList = null;
            List<OuterBidBaseTabulation> outerBidBaseTabulationList = outerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, projectId, 1);
            return R.ok();
        }
    }


    @ApiOperation(value = "投标报价纵向对比-单个供应商", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getVerticalStatisOne", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getVerticalStatisOne(Long projectId, Integer innerOuterType, Integer jieDuan, Long supplyCompanyId) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);
        SupplyCompany supplyCompany = supplyCompanyService.findOne(supplyCompanyId);
        hashMap.put("supplyCompany.id", supplyCompanyId);
        List<BiddingCompany> companyItemList = biddingCompanyService.getListLogic(hashMap, null);

        if (innerOuterType == 1) {
            //投标报价纵向对比-内线
            List<VerticalStatisCollectVo> tempList = analysisService.getVerticalStatis(companyList, projectId, jieDuan);
            List<VerticalStatisCollectVo> toList = analysisService.getVerticalStatisOne(tempList, supplyCompany, companyItemList, jieDuan);
            return R.ok(toList);
        } else {
            //投标报价纵向对比-内线(暂无)
            List<OuterTabulation> outerTabulationList = null;
            List<OuterBidBaseTabulation> outerBidBaseTabulationList = outerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, projectId, 1);
            return R.ok();
        }
    }


    @ApiOperation(value = "综合单价对比分析", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getComprehensiveUnitPrice", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getComprehensiveUnitPrice(Long projectId, Integer innerOuterType, Integer jieDuan) throws InvocationTargetException, IllegalAccessException {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);

        if (innerOuterType == 1) {
            //综合单价对比分析-内线
            List<ComprehensiveUnitPriceCollectVo> sortedList = analysisService.getComprehensiveUnitPrice(companyList, projectId, jieDuan);

            return R.ok(sortedList);
        } else {
            //综合单价对比分析-内线(暂无)
            List<OuterTabulation> outerTabulationList = null;
            List<OuterBidBaseTabulation> outerBidBaseTabulationList = outerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, projectId, 1);

            return R.ok();
        }
    }


    @ApiOperation(value = "综合单价对比分析-查看单个供应商", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getComprehensiveUnitPriceOne", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getComprehensiveUnitPriceOne(Long projectId, Integer innerOuterType, Integer jieDuan, Long supplyCompanyId) throws InvocationTargetException, IllegalAccessException {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);
        SupplyCompany supplyCompany = supplyCompanyService.findOne(supplyCompanyId);
        hashMap.put("supplyCompany.id", supplyCompanyId);
        List<BiddingCompany> companyItemList = biddingCompanyService.getListLogic(hashMap, null);

        if (innerOuterType == 1) {
            //综合单价对比分析-内线
            List<ComprehensiveUnitPriceCollectVo> tempList = analysisService.getComprehensiveUnitPrice(companyList, projectId, jieDuan);
            List<ComprehensiveUnitPriceCollectVo> toList = analysisService.getComprehensiveUnitPriceOne(tempList, supplyCompany, companyItemList, jieDuan);

            return R.ok(toList);
        } else {
            //综合单价对比分析-内线(暂无)
            List<OuterTabulation> outerTabulationList = null;
            List<OuterBidBaseTabulation> outerBidBaseTabulationList = outerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, projectId, 1);

            return R.ok();
        }
    }


    @ApiOperation(value = "生成 实施定标 标阶段的数据沉淀分析", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/generatePrecipitateSsdb", produces = {"application/json"}, method = RequestMethod.POST)
    public Result generatePrecipitateSsdb(Long projectId) throws InvocationTargetException, IllegalAccessException {
        //再次生成时删除原来的数据
        precipitateSsdbService.getRepository().deleteByFlagAndProjectId(1, projectId);
        analysisService.handlePrecipitateSsdb(projectId);
        return R.ok();
    }


    @ApiOperation(value = "生成定标标阶段的数据沉淀分析", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/generatePrecipitate", produces = {"application/json"}, method = RequestMethod.POST)
    public Result generatePrecipitate(Long projectId, Long choiceProjectId, Long choiceSupplyCompanyId) throws InvocationTargetException, IllegalAccessException {
        if (choiceProjectId == null || choiceSupplyCompanyId == null) {
            //再次生成时删除原来的数据
            precipitateDbService.getRepository().deleteByFlagAndProjectId(1, projectId);
            analysisService.handlePrecipitate(projectId);
        } else {
            //添加对比项目
            analysisService.handlePrecipitateToProject(projectId, choiceProjectId, choiceSupplyCompanyId);
        }

        return R.ok();
    }


    @ApiOperation(value = "生成定标阶段的沉淀分析数据时选择对比项目", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/choiceProject", produces = {"application/json"}, method = RequestMethod.POST)
    public Result choiceProject(Long projectId, String province, String city) throws InvocationTargetException, IllegalAccessException {
        return R.ok(analysisService.choiceProject(projectId, province, city));
    }


    @ApiOperation("导出投标报价纵向对比内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportZxdb", method = RequestMethod.GET)
    public Result exportZxdb(Long projectId, Integer innerOuterType, Integer jieDuan) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);

        List<VerticalStatisCollectVo> sortedList = null;
        if (innerOuterType == 1) {
            //投标报价纵向对比-内线
            sortedList = analysisService.getVerticalStatis(companyList, projectId, jieDuan);
        }
        String fileName = companyList.get(0).getProject().getName();
        XSSFWorkbook workbook = analysisService.exportZxdb(sortedList);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "投标报价横向对比-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation("导出综合单价对比内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportZhdj", method = RequestMethod.GET)
    public Result exportZhdj(Long projectId, Integer innerOuterType, Integer jieDuan) throws InvocationTargetException, IllegalAccessException {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("innerOuterType", innerOuterType);
        List<BiddingCompany> companyList = biddingCompanyService.getListLogic(hashMap, null);

        List<ComprehensiveUnitPriceCollectVo> sortedList = null;
        if (innerOuterType == 1) {
            //综合单价对比分析-内线
            sortedList = analysisService.getComprehensiveUnitPrice(companyList, projectId, jieDuan);
        }
        String fileName = companyList.get(0).getProject().getName();
        XSSFWorkbook workbook = analysisService.exportZhdj(sortedList);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "综合单价对比-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


}

